package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.R;
import com.atguigu.commonutils.ordervo.CourseWebVoOrder;
import com.atguigu.commonutils.ordervo.UcenterMemberOrder;
import com.atguigu.eduorder.client.EduClient;
import com.atguigu.eduorder.client.UcenterClient;
import com.atguigu.eduorder.entity.*;
import com.atguigu.eduorder.entity.query.HistoryQuray;
import com.atguigu.eduorder.service.HistoryService;
import com.atguigu.eduorder.service.LikeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gengky
 * @since 2022-04-15
 */
@RestController
@RequestMapping("/eduorder/history")
public class HistoryController {

    @Autowired
    LikeService likeService;

    @Autowired
    HistoryService historyService;

    @Autowired
    private EduClient eduClient;

    @Autowired
    private UcenterClient ucenterClient;




    @ApiOperation(value = "分页学习历史列表")
    @PostMapping("PageCondition/{current}/{limit}")
    public R pageHistoryCondition(@PathVariable long current, @PathVariable long limit,
                                  @RequestBody(required = false) HistoryQuray historyQuray){
        //创建page对象
        Page<History> historyPage=new Page<>(current,8);
        //构建条件
        QueryWrapper<History> wrapper=new QueryWrapper<>();

        //多条件组合查询（动态sql组合）//构造条件（这里“name”是mysql中的列名，后面一样）
        if (!StringUtils.isEmpty(historyQuray.getNickname())){
            wrapper.like("nickname",historyQuray.getNickname());
        }
        if (!StringUtils.isEmpty(historyQuray.getCourseTitle())){
            wrapper.eq("course_title",historyQuray.getCourseTitle());
        }
        if (!StringUtils.isEmpty(historyQuray.getCourseId())){
            wrapper.eq("course_id",historyQuray.getCourseId());
        }
        if (!StringUtils.isEmpty(historyQuray.getVideoTitle())){
            wrapper.eq("video_title",historyQuray.getVideoTitle());
        }

        if (!StringUtils.isEmpty(historyQuray.getBegin())){
            wrapper.ge("gmt_create",historyQuray.getBegin());
        }
        if (!StringUtils.isEmpty(historyQuray.getEnd())){
            wrapper.le("gmt_create", historyQuray.getEnd());
        }
        //排序
        wrapper.orderByDesc("gmt_create");
        //调用方法实现条件查询分页
        historyService.page(historyPage,wrapper);
        //
        List<History> records = historyPage.getRecords();
        //
        long total=historyPage.getTotal();

        return R.ok().data("total",total).data("rows",records);

    }



    @ApiOperation("添加一条历史记录")
    @PostMapping("addHistory/{courseId}/{videoId}/{memberId}")
    public R addHistory(@PathVariable("courseId") String courseId,
                        @PathVariable("videoId") String videoId,
                        @PathVariable("memberId") String memberId) {

        //通过远程调用 根据用户ID 获取用户信息，调用 service-ucenter 的 UcenterMemberController
        UcenterMemberOrder member = ucenterClient.getUserInfoOrder(memberId);
        //通过远程调用 根据课程ID 获取课程信息，
        CourseWebVoOrder course = eduClient.getCourseInfoOrder(courseId);

        History history=new History();
        history.setCourseId(courseId);
        history.setVideoId(videoId);

        //根据 videoID 添加 videoTitle
        List<EduVideo> videoName = eduClient.getVideoByVideoId(videoId);
        history.setVideoTitle(videoName.get(0).getTitle());

        history.setCourseCover(course.getCover());
        history.setCourseTitle(course.getTitle());
        history.setUserId(memberId);
        history.setNickname(member.getNickname());
        history.setGmtCreate(new Date());
        history.setGmtModified(new Date());

        System.out.println(history.toString());

        historyService.save(history);
        return R.ok();
    }


    @ApiOperation("根据会员ID查询历史课程")
    @GetMapping("getHistoryByNumberId/{memberid}")
    public R getHistoryByNumberId(@PathVariable String memberid){
        QueryWrapper<History> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",memberid);
        queryWrapper.orderByAsc("gmt_create");
        List<History> list = historyService.list(queryWrapper);
        //手动去重，linkedHashmap
        LinkedHashMap<String,History> linkedHashMap=new LinkedHashMap<>();
        for (int i = 0; i < list.size(); i++) {
            //根据课程名称去重
            linkedHashMap.put(list.get(i).getCourseTitle(),list.get(i));
        }
        List<History> ans=new ArrayList<>();
        //TODO：限制4条记录
        linkedHashMap.forEach((key,value)->{
            ans.add(value);
        });
        System.out.println(ans.size());
        System.out.println(ans.toString());
        return R.ok().data("historyCourses",ans);
    }


    @GetMapping("getHistoryListByNumberId/{memberid}")
    public List<History> getHistoryListByNumberId(@PathVariable String memberid){
        QueryWrapper<History> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",memberid);
        queryWrapper.orderByDesc("gmt_create");
        queryWrapper.last("limit 1");
        List<History> list = historyService.list(queryWrapper);
        return list;
    }

}

